<script>
import shop from "/src/js/shop";
import BoxInI18nParamDialog from "/src/views/manage/shop/goods/components/BoxInI18nParamDialog.vue";

export default {
  components: {BoxInI18nParamDialog},
  data() {
    return {
      shop,
      visible: [],
      show: false,
      requestParam: {
        bodyJson: [
          {
            "type": "fileIdOfVideo",
            "value": 592191893413893
          },
          {
            "type": "fileIdOfImg",
            "value": 592191893413893
          },
        ],

        params: [
          {
            "paramId": 1,
            "value": 592191893413893
          },
          {
            "paramId": 2,
            "value": 592191893413893
          },
        ],

        attrJson: [
          {
            "attrId": 1,
            "value": 592191893413893
          },
          {
            "attrId": 2,
            "value": 592191893413893
          },
        ],


        detailJson: [
          {
            type: "fileIdOfImg",
            value: 592191893413893
          },
          {
            type: "fileIdOfVideo",
            value: 592191893413893
          }
        ],
        "bodyJsonStr": null,
        "costPrice": null,
        "detailJsonStr": null,
        "fileIdOfMain": 592191893413893,
        "gmtCreate": null,
        "gmtModified": null,
        "id": null,
        "isRecommend": null,
        "name": "KY016-3 石子生产线 轮胎式移动砂石线设备 矿山专用车载式破碎站",
        "price": null,
        "priority": null,
        salesVolumeShowNumber: null,
        stockNumber: null,
        "typeId": null
      },
      typeIds: [],
      typeList: [],
      paramList: [],
      paramMap: [],
      attrList: [],
      attrMap: {},
      // 属性可选项
      attrSelect: [
        {
          attrId: 1,
          selects: ["1", "2", "3"]
        }
      ],
      isInit: false
    }
  },
  created() {
    this.getParamList();
    this.getTypeList();
    this.getAttrList();
  },
  mounted() {
    this.visible = [];
    // 初始化visible
    for (let i = 0; i < this.requestParam.bodyJson.length; i++) {
      this.visible.push(false);
    }
  },
  watch: {
    "typeIds": {
      handler: function (val, oldVal) {
        if (val.length === 0) {
          this.requestParam.typeId = null;
        } else {
          this.requestParam.typeId = val[val.length - 1];
        }
      },
      deep: true
    },
    "requestParam.bodyJson": {
      handler: function (val, oldVal) {
        this.visible = [];
        // 初始化visible
        for (let i = 0; i < this.requestParam.bodyJson.length; i++) {
          this.visible.push(false);
        }
      },
      deep: true
    },
    "requestParam.isHasAttr": {
      handler: function (val, oldVal) {
        if(!this.isInit){
          return;
        }
        if (!val) {
          this.requestParam.attrs = [];
          this.requestParam.attrGroups = [];
          this.setAttrSelect();
        }
      },
      deep: true
    },
    "requestParam.attrs": {
      handler: function (val, oldVal) {
        if(!this.isInit){
          return;
        }
        this.requestParam.attrGroups = [];
        this.addSubGoods();
        this.setAttrSelect();
      },
      deep: true
    },
    "requestParam.attrGroups": {
      handler: function (val, oldVal) {
        // if(!this.isInit){
        //   return;
        // }
        this.setAttrSelect();
        // 如果为SKU商品，则计算当前库存
        if (this.requestParam.isHasAttr) {
          let stockNumber = 0;
          for (let i = 0; i < this.requestParam.attrGroups.length; i++) {
            stockNumber += parseInt(this.requestParam.attrGroups[i].stockNumber);
          }
          this.requestParam.stockNumber = stockNumber;
        }
      },
      deep: true
    }
  },
  methods: {
    /**
     * 设置属性可选项
     * 根据在子商品中，已填写的属性，设置属性可选项
     */
    setAttrSelect() {
      this.attrSelect = [];
      let attrIdMap = {};
      for (let i = 0; i < this.requestParam.attrs.length; i++) {
        attrIdMap[this.requestParam.attrs[i].attrId] = [];
      }
      for (let i = 0; i < this.requestParam.attrGroups.length; i++) {
        for (let j = 0; j < this.requestParam.attrGroups[i].attrs.length; j++) {
          if (attrIdMap[this.requestParam.attrGroups[i].attrs[j].attrId]) {
            attrIdMap[this.requestParam.attrGroups[i].attrs[j].attrId].push(this.requestParam.attrGroups[i].attrs[j].value);
          }
        }
      }
      // 去重
      for (let key in attrIdMap) {
        attrIdMap[key] = [...new Set(attrIdMap[key])];
      }


      // 再根据attrIdMap，设置attrSelect
      for (let key in attrIdMap) {
        this.attrSelect.push({
          attrId: key,
          selects: attrIdMap[key]
        });
      }
    },
    addSubGoods() {
      let subGoods = {price: "",stockNumber:0, attrs: []};
      for (let i = 0; i < this.requestParam.attrs.length; i++) {

        subGoods.attrs.push({
          attrId: this.requestParam.attrs[i].attrId,
          value: ""
        });

      }
      this.requestParam.attrGroups.push(subGoods);
    },
    moveLeft(index) {
      if (index === 0) {
        return;
      }
      let temp = this.requestParam.bodyJson[index];
      this.requestParam.bodyJson[index] = this.requestParam.bodyJson[index - 1];
      this.requestParam.bodyJson[index - 1] = temp;
    },
    moveRight(index) {
      if (index === this.requestParam.bodyJson.length - 1) {
        return;
      }
      let temp = this.requestParam.bodyJson[index];
      this.requestParam.bodyJson[index] = this.requestParam.bodyJson[index + 1];
      this.requestParam.bodyJson[index + 1] = temp;
    },
    // 检测bodyJson是否超过15个
    checkBodyJson() {
      if (this.requestParam.bodyJson.length >= 15) {
        this.$message.error("最多只能添加15个");
        return false;
      }
      return true;
    },
    editImgInBodyJson(index) {
      this.$kt.file.chooseImageOne().then(res => {
        let loading = this.$loading({
          lock: true,
          text: '上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$kt.request.uploadFile({
          file: res.file,
          groupCode: "goods",
          stateSuccess: async (res) => {
            this.requestParam.bodyJson[index].type = "fileIdOfImg";
            this.requestParam.bodyJson[index].value = res.data.id;
            loading.close();
          },
          stateFail: (res) => {
            this.$message.error(res.errMsg);
            loading.close();
          }
        });
      });
    },
    editVideoInBodyJson(index) {
      this.$kt.file.chooseVideoOne().then(res => {
        let loading = this.$loading({
          lock: true,
          text: '上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$kt.request.uploadFile({
          file: res.file,
          groupCode: "goods",
          stateSuccess: async (res) => {
            this.requestParam.bodyJson[index].type = "fileIdOfVideo";
            this.requestParam.bodyJson[index].value = res.data.id;
            loading.close();
          },
          stateFail: (res) => {
            this.$message.error(res.errMsg);
            loading.close();
          }
        });
      });
    },


    chooseImgInBodyJson(index) {
      if (!this.checkBodyJson()) {
        return;
      }
      this.$kt.file.chooseImageOne().then(res => {
        let loading = this.$loading({
          lock: true,
          text: '上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$kt.request.uploadFile({
          file: res.file,
          groupCode: "goods",
          stateSuccess: async (res) => {
            this.requestParam.bodyJson.push({
              type: "fileIdOfImg",
              value: res.data.id
            });
            loading.close();
          },
          stateFail: (res) => {
            this.$message.error(res.errMsg);
            loading.close();
          }
        });
      });
    },
    chooseVideoInBodyJson() {
      if (!this.checkBodyJson()) {
        return;
      }
      this.$kt.file.chooseVideoOne().then(res => {
        let loading = this.$loading({
          lock: true,
          text: '上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$kt.request.uploadFile({
          file: res.file,
          groupCode: "goods",
          stateSuccess: async (res) => {
            this.requestParam.bodyJson.push({
              type: "fileIdOfVideo",
              value: res.data.id
            });
            loading.close();
          },
          stateFail: (res) => {
            this.$message.error(res.errMsg);
            loading.close();
          }
        });
      });
    },
    chooseImgInDetailJson() {
      this.$kt.file.chooseImageOne().then(res => {
        let loading = this.$loading({
          lock: true,
          text: '上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$kt.request.uploadFile({
          file: res.file,
          groupCode: "goods",
          stateSuccess: async (res) => {
            this.requestParam.detailJson.push({
              type: "fileIdOfImg",
              value: res.data.id
            });
            loading.close();
          },
          stateFail: (res) => {
            this.$message.error(res.errMsg);
            loading.close();
          }
        });
      });
    },
    chooseVideoInDetailJson() {
      this.$kt.file.chooseVideoOne().then(res => {
        let loading = this.$loading({
          lock: true,
          text: '上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$kt.request.uploadFile({
          file: res.file,
          groupCode: "goods",
          stateSuccess: async (res) => {
            this.requestParam.detailJson.push({
              type: "fileIdOfVideo",
              value: res.data.id
            });
            loading.close();
          },
          stateFail: (res) => {
            this.$message.error(res.errMsg);
            loading.close();
          }
        });
      });
    },
    moveLeftInD(index) {
      if (index === 0) {
        return;
      }
      let temp = this.requestParam.detailJson[index];
      this.requestParam.detailJson[index] = this.requestParam.detailJson[index - 1];
      this.requestParam.detailJson[index - 1] = temp;
    },
    moveRightInD(index) {
      if (index === this.requestParam.detailJson.length - 1) {
        return;
      }
      let temp = this.requestParam.detailJson[index];
      this.requestParam.detailJson[index] = this.requestParam.detailJson[index + 1];
      this.requestParam.detailJson[index + 1] = temp;
    },
    open(item) {
      this.isInit = false;
      if (item) {
        if (item.typeId) {
          if (item.type?.parentId) {
            this.typeIds = [item.type?.parentId, item.typeId];
          } else {
            this.typeIds = [item.typeId];
          }
        } else {
          this.typeIds = [];
        }
        this.requestParam = this.$kt.util.deepCopy(item);
      } else {
        this.requestParam = {
          bodyJson: [],
          detailJson: [],
          params: [],
          attrs: [],
          attrGroups: [],
          isHasAttr: false,
          "bodyJsonStr": null,
          "costPrice": null,
          "detailJsonStr": null,
          "fileIdOfMain": null,
          "gmtCreate": null,
          "gmtModified": null,
          "id": null,
          "isRecommend": null,
          "name": null,
          "price": null,
          "priority": null,
          salesVolumeShowNumber: null,
          stockNumber: null,
          "typeId": null
        }
      }
      this.show = true;
      setTimeout(()=>{
        this.isInit = true;
      },200);
    },
    save() {
      let requestParam = this.$kt.util.deepCopy(this.requestParam);
      requestParam.bodyJsonStr = JSON.stringify(this.requestParam.bodyJson);
      requestParam.detailJsonStr = JSON.stringify(this.requestParam.detailJson);
      requestParam.bodyJson = null;
      requestParam.detailJson = null;
      let loading = this.$loading({
        lock: true,
        text: '保存中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$kt.request.send({
        uri: "/business-shop-web/admin/shopGoods/saveNew",
        data: requestParam,
        stateSuccess: (res) => {
          loading.close();
          this.show = false;
          this.$emit("saveSuccess");
        },
        stateFail: (res) => {
          loading.close();
          this.$message.error(res.errMsg);
        }
      });
    },
    getTypeList() {
      this.$kt.request.send({
        uri: "/business-shop-web/shopGoodsType/getAll",
        stateSuccess: (res) => {
          let bodyData = res.data;
          this.typeList = [];
          // 将所有parent_id为空的数据放到list中
          for (let i = 0; i < bodyData.length; i++) {
            if (!bodyData[i].parentId) {
              this.typeList.push(bodyData[i]);
            }
          }

          // 获取所有的子分类，放进list的children中
          for (let i = 0; i < this.typeList.length; i++) {
            this.typeList[i].children = [];
            for (let j = 0; j < bodyData.length; j++) {
              if (this.typeList[i].id === bodyData[j].parentId) {
                this.typeList[i].children.push(bodyData[j]);
              }
            }
          }
          this.$forceUpdate();

        }
      });
    },
    getParamList() {
      this.$kt.request.send({
        uri: "/business-shop-web/shopGoodsParam/getAll",
        stateSuccess: (res) => {
          this.paramList = res.data;
          this.paramMap = {};
          for (let i = 0; i < this.paramList.length; i++) {
            this.paramMap[this.paramList[i].id] = this.paramList[i];
          }
        }
      });
    },
    getAttrList() {
      this.$kt.request.send({
        uri: "/business-shop-web/shopGoodsAttr/getAll",
        stateSuccess: (res) => {
          this.attrList = res.data;
          this.attrMap = {};
          for (let i = 0; i < this.attrList.length; i++) {
            this.attrMap[this.attrList[i].id] = this.attrList[i];
          }
        }
      });
    }
  }
}

</script>

<template>
  <el-dialog
      title="参数国际化"
      width="800px"
      v-model="show">
    <el-scrollbar style="height: calc(100vh - 150px);width:100%">
      <div
       v-for="(item,index) in requestParam.params"
      >
        <box-in-i18n-param-dialog
        :param="item"
        ></box-in-i18n-param-dialog>
      </div>
    </el-scrollbar>

  </el-dialog>

</template>

<style scoped lang="scss">
.in-json-box {
  display: inline-block;
  width: 130px;
  height: 100px;
  text-align: center;
  border: 1px solid #ebeef5;
  margin: 10px;
  border-radius: 10px;
  cursor: pointer;

  .move {
    display: flex;
    justify-content: space-between;
    padding: 5px;
  }
}

.table {
  width: 100%;
  border-collapse: collapse;

  tr {
    border: 1px solid #ebeef5;

    td {
      padding: 10px;
      border-right: 1px solid #ebeef5;
    }
  }
}

.tag-btn {
  display: inline-block;
  padding: 0 5px 0 5px;
  margin-right: 10px;
  border: 1px solid #ebeef5;
  cursor: pointer;
  border-radius: 10px;
}

.tag-btn:hover {
  transform: scale(1.05);
}

.tag-btn:active {
  transform: scale(1);
}

</style>